package com.cn.aam.checaiduo.ui.useraccess;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.KeyBoardObserverActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.bean.UserB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.center.SharePreferenceCenter;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.utils.AuthUtil;
import com.cn.aam.checaiduo.utils.MyEditTextUtils;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.StringUtil;
import com.cn.aam.checaiduo.widget.WMToast;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录操作
 */
public class LoginActivity extends KeyBoardObserverActivity {

    @BindView(R.id.iv_app_logo)
    ImageView ivAppLogo;

    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_pwd)
    EditText etPwd;

    @BindView(R.id.cb_save_pwd)
    CheckBox cbSavePwd;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;

    @BindView(R.id.iv_show_pwd)
    ImageView ivShowPwd;//是否显示密码


    private boolean isShowPwd = false;//是否显示密码

    private String username;
    private String password;

    public static Intent newInstance(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        return intent;
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_login;
    }


    /**
     * 初始化数据
     */
    @Override
    protected void onGenerate() {
        SharePreferenceCenter shareCenter = SharePreferenceCenter.getInstance();
        username = shareCenter.getAppSharePre().getUsername();
        password = shareCenter.getAppSharePre().getPassword();
    }

    /**
     * 初始化视图
     */
    @Override
    protected void initView() {
        //Toolbar
        ToolBarManager.with(this, WMContent)
                .setBackgroundColor(R.color.white)
                .setTitle("")
                .setNavigationIcon(R.drawable.ic_nav_close_circle);

        //chebox的变化
        cbSavePwd.setChecked(!TextUtils.isEmpty(password));

        //账号
        etAccount.setText(!TextUtils.isEmpty(username) ? username : "");
        MyEditTextUtils.setSeletionEnd(etAccount);

        //密码
        etPwd.setText(!TextUtils.isEmpty(password) ? password : "");


    }

    /**
     * 登录按钮
     */
    @OnClick(R.id.btn_login)
    public void clickOnLogin() {
        //if (MyViewsUtils.isFastDoubleClick()) return;
        if (checkValue()) actionLogin();
    }

    /**
     * 通过为 true 不同过为false
     * 此处可以无限增加各种检查条件
     */
    private boolean checkValue() {
        username = MyEditTextUtils.getContent(etAccount);
        password = MyEditTextUtils.getContent(etPwd);

        if (TextUtils.isEmpty(username)) {
            WMToast.normal("账号/手机号为空");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            WMToast.normal("密码输入为空");
            return false;
        }
        if (!AuthUtil.isMobileNo(username)) {
            WMToast.normal("请确保手机号格式输入正确");
            return false;
        }
        if (!StringUtil.isValidateOr(password)) {
            WMToast.normal("请确保密码是6~20位字母或数字的组成");
            return false;
        }
        return true;
    }

    /**
     * 开始登录
     */
    private void actionLogin() {
        Logger.e("点击登录");
        RetrofitHome.getInstance()
                .getUserApi()
                .login(username, password)
                .compose(RxSchedulers.<NormalResponseB<UserB>>toMain())
                .subscribe(new OnRequestV2Listener<UserB>(this) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    protected String getProgressBarContent() {
                        return "登录中...";
                    }

                    @Override
                    public void onNext(NormalResponseB<UserB> value) {
                        super.onNext(value);
                        Logger.e("进入onNext");
                        if (value.getCode() == Const.REQUEST_FAILED) return;
                        //save password
                        SharePreferenceCenter sharePreCenter = SharePreferenceCenter.getInstance();
                        if (cbSavePwd.isChecked())
                            sharePreCenter.savePhonePwd(username, password);
                        else
                            sharePreCenter.savePhone(username);

                        //save user data
                        UserCenter userCneter = UserCenter.getInstance();
                        userCneter.setUser(value.getData());
                        MobclickAgent.onProfileSignIn(username);//umeng帐号统计
                        //dispatch page
                        onBackWithSuccess();
                    }
                });
    }


    /**
     * 立即注册
     */
    @OnClick(R.id.btn_register)
    public void clickOnRegister() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        startActivity(RegisterActivity.newInstance(mContext));
    }

    /**
     * 忘记密码
     */
    @OnClick(R.id.tv_forget_pwd)
    public void clickOnForgetPwd() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        startActivity(ForgetPwdActivity.newInstance(mContext));
    }

    /**
     * 显示密码
     */
    @OnClick(R.id.iv_show_pwd)
    void togglePassword() {
        if (MyViewsUtils.isFastDoubleClick()) return;
        ivShowPwd.setActivated(isShowPwd = !isShowPwd);
        MyEditTextUtils.changePasswordStatus(etPwd, isShowPwd);
    }

    /**
     * 登录成功
     */
    public void onBackWithSuccess() {
        AppData.isGestureVerify = true;
        setResult(RESULT_OK);
        closePage();
    }

    /**
     * 取消登录
     */
    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        closePage();
    }

    private void closePage() {
        finish();
        overridePendingTransition(0, R.anim.slide_out_from_bottom);
    }

    /**
     * 键盘显示时
     */
    @Override
    protected void onKeyBoardShow() {
        if (ivAppLogo != null)
            MyViewsUtils.hideAllViews(ivAppLogo);
    }

    /**
     * 键盘隐藏时
     */
    @Override
    protected void onKeyBoardDismiss() {
        if (ivAppLogo != null)
            MyViewsUtils.showAllViews(ivAppLogo);
    }


}
